package com.cmy.framework_base.basics

import com.cmy.framework_network.apiresponse.NetworkResponse
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/**
 * @name:
 *  BaseModel
 * @package:
 *  com.cmy.framework_base.basics
 * @date:
 *  2023/3/116:31
 * @author
 *    cmy
 * @description
 * 基础Response，实现数据初步整合
 */
abstract class BasicsResponse {
    /**
     * 处理数据，并且将数据发送Main线程
     */
    suspend fun <T : Any> networkResponse(
        response: NetworkResponse<T>?,
        onSuccess: (data: T) -> Unit,
        onFailure: (msg: String?) -> Unit
    ) {
        withContext(Dispatchers.Main) {
            response?.let {
                when (it) {
                    is NetworkResponse.Success -> {
                        onSuccess(it.body)
                    }
                    is NetworkResponse.ApiError -> {
                        onFailure(it.body.toString())
                    }
                    is NetworkResponse.NetworkError -> {
                        onFailure(it.message.toString())
                    }
                    is NetworkResponse.UnknownError -> {
                        onFailure(it.error?.message)
                    }
                }
            }


        }
    }
}